﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PlayerTest.Player.Event;
using System.Diagnostics;
using System.Collections.Specialized;
using System.Net;
using System.Xml;

namespace PlayerTest.Player.Handler
{
    class UserHandler
    {
    #region Event Sending
        public event UserEventHandler EventHandler;
        /// <summary>
        /// Player에게 이벤트 전송
        /// </summary>
        /// <param name="arg"></param>
        private void SendUserEvent(UserEventArgs arg)
        {
            // 연결된 모든 함수에 이벤트 전송
            UserEventHandler handler = EventHandler;
            if (handler != null) handler(this, arg);
        }
    #endregion

        private string m_ID = null;
        private string m_PW = null;
        private int userID;
        public int UserID
        {
            get { return userID; }
        }
        public string LoginID
        {
            get { return m_ID; }
        }
        //public string 

        #region Login
        /// <summary>
        /// 지정된 ID와 비밀번호로 로그인합니다.
        /// </summary>
        /// <param name="ID">ID</param>
        /// <param name="PW">비밀번호</param>
        public void Login(string ID, string PW)
        {
            if (ID==null || PW==null || ID.Length==0 || PW.Length==0)
            {
                UserEventArgs arg = new UserEventArgs(UserEventArgs.eventtype.ERROR);
                arg.Result = false;
                arg.Message = "ID와 비밀번호를 입력해 주세요.";
                SendUserEvent(arg);
            }
            this.m_ID = ID;
            this.m_PW = PW;

            try
            {
                String pageurl = "http://winz.myvnc.com/sub/User/user_appLogin.jsp";
                NameValueCollection myNVC = new NameValueCollection();
                WebClient web_client = new WebClient();

                myNVC.Add("user_id", m_ID);
                myNVC.Add("user_pw", m_PW);
                web_client.QueryString = myNVC;

                Trace.WriteLine(String.Format("[Login] 서버에 로그인 합니다..."));

                web_client.UploadValuesCompleted += new UploadValuesCompletedEventHandler(Login_Completed);
                web_client.UploadValuesAsync(new Uri(pageurl), myNVC);
            }
            catch (WebException e)
            {
                Trace.WriteLine(String.Format("[Login] 오류발생!"));
                Trace.WriteLine(e.StackTrace);
            }
        }


        /// <summary>
        /// Asynchronous
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Login_Completed(object sender, UploadValuesCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                String xmlresult = Encoding.UTF8.GetString(e.Result);
                UserEventArgs   arg = new UserEventArgs(UserEventArgs.eventtype.LOGIN);

                if (true == parseLogin(xmlresult))
                {
                    // 로그인 성공
                    arg.Result = true;
                }
                else
                {
                    arg.Result = false;
                }
                SendUserEvent(arg);
            }
            else
            {
                UserEventArgs arg = new UserEventArgs(UserEventArgs.eventtype.ERROR);
                arg.Result = false;
                arg.Message = "로그인 서버에 접속하는 도중 오류가 발생하였습니다!";
                SendUserEvent(arg);
            }
        }

        private bool parseLogin(String xml)
        {
            bool result = false;
            // XML을 파싱한다.
            XmlDocument xDoc = new XmlDocument();
            xDoc.LoadXml(xml);

            XmlElement rootNode = (XmlElement)xDoc.DocumentElement;
            result = Convert.ToBoolean(rootNode.GetAttribute("Result"));

            if (result)
            {
                userID = Convert.ToInt32(rootNode.LastChild.Attributes["ID"].Value);
                Trace.WriteLine(String.Format("[Login] 로그인 성공 / UserID : {0}", userID));
            }
            else
            {
                Trace.WriteLine("[Login] 로그인 실패!!");

                XmlNodeList list = rootNode.GetElementsByTagName("Item");
                if (list.Count > 0)
                {
                    Trace.WriteLine(String.Format("[Login] {0}", list[0].FirstChild.Value));
                }
            }

            return result;
        }
        #endregion

        #region Logout
        public void Logout()
        {
            if (m_ID == null || m_PW==null)
            {
                UserEventArgs arg = new UserEventArgs(UserEventArgs.eventtype.ERROR);
                arg.Result = false;
                arg.Message = "로그인 상태가 아닙니다!";
                SendUserEvent(arg);
            }

            try
            {
                String pageurl = "http://winz.myvnc.com/sub/User/user_appLogout.jsp";
                NameValueCollection myNVC = new NameValueCollection();
                WebClient web_client = new WebClient();

                web_client.QueryString = myNVC;

                Trace.WriteLine(String.Format("[Logout] 로그아웃 합니다.."));

                web_client.UploadValuesCompleted += new UploadValuesCompletedEventHandler(Logout_Completed);
                web_client.UploadValuesAsync(new Uri(pageurl), myNVC);
            }
            catch (WebException e)
            {
                Trace.WriteLine(String.Format("[Logout] 오류발생!"));
                Trace.WriteLine(e.StackTrace);
            }
            
        }


        /// <summary>
        /// Asynchronous
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Logout_Completed(object sender, UploadValuesCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                String xmlresult = Encoding.UTF8.GetString(e.Result);
                parseLogout(xmlresult);
            }
            else
            {
                UserEventArgs arg = new UserEventArgs(UserEventArgs.eventtype.ERROR);
                arg.Result = false;
                arg.Message = "서버에 접속하는 도중 오류가 발생하였습니다!";
                SendUserEvent(arg);
            }
        }

        private bool parseLogout(String xml)
        {
            bool result = false;
            // XML을 파싱한다.
            XmlDocument xDoc = new XmlDocument();
            xDoc.LoadXml(xml);

            XmlElement rootNode = (XmlElement)xDoc.DocumentElement;
            result = Convert.ToBoolean(rootNode.GetAttribute("Result"));

            if (result)
            {
                Trace.WriteLine(String.Format("[Logout] 로그아웃 되었습니다."));
            }

            return result;
        }

    #endregion

        #region Join
        /// <summary>
        /// 지정된 ID와 비밀번호로 로그인합니다.
        /// </summary>
        /// <param name="ID">ID</param>
        /// <param name="PW">비밀번호</param>
        public void Join(string email, string nick, string pw)
        {
            try
            {
                String pageurl = "http://winz.myvnc.com/sub/User/doMemberJoin.jsp";
                NameValueCollection myNVC = new NameValueCollection();
                WebClient web_client = new WebClient();
                myNVC.Add("email", email);
                myNVC.Add("user_name", nick);
                myNVC.Add("user_pw", pw);
                web_client.QueryString = myNVC;

                Trace.WriteLine(String.Format("[Join] 서버에 로그인 합니다..."));

                web_client.UploadValuesCompleted += new UploadValuesCompletedEventHandler(Join_Completed);
                web_client.UploadValuesAsync(new Uri(pageurl), myNVC);
            }
            catch (WebException e)
            {
                Trace.WriteLine(String.Format("[Login] 오류발생!"));
                Trace.WriteLine(e.StackTrace);
            }
        }


        /// <summary>
        /// Asynchronous
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Join_Completed(object sender, UploadValuesCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                String xmlresult = Encoding.UTF8.GetString(e.Result);
                UserEventArgs arg = new UserEventArgs(UserEventArgs.eventtype.JOIN);

                if (true == parseJoin(xmlresult))
                {
                    // 회원가입 성공
                    arg.Result = true;
                }
                else
                {
                    arg.Result = false;
                }
                SendUserEvent(arg);
            }
            else
            {
                UserEventArgs arg = new UserEventArgs(UserEventArgs.eventtype.ERROR);
                arg.Result = false;
                arg.Message = "로그인 서버에 접속하는 도중 오류가 발생하였습니다!";
                SendUserEvent(arg);
            }
        }

        private bool parseJoin(String xml)
        {
            bool result = false;
            // XML을 파싱한다.
            XmlDocument xDoc = new XmlDocument();
            xDoc.LoadXml(xml);

            XmlElement rootNode = (XmlElement)xDoc.DocumentElement;
            result = Convert.ToBoolean(rootNode.GetAttribute("Result"));

            if (result)
            {
                userID = Convert.ToInt32(rootNode.LastChild.Attributes["ID"].Value);
                Trace.WriteLine(String.Format("[Join] 가입 성공 / UserID : {0}", userID));
            }
            else
            {
                Trace.WriteLine("[Join] 가입 실패!!");

                XmlNodeList list = rootNode.GetElementsByTagName("Item");
                if (list.Count > 0)
                {
                    Trace.WriteLine(String.Format("[Login] {0}", list[0].FirstChild.Value));
                }
            }

            return result;
        }
        #endregion
    }
}
